package main

import (
	"crypto/rand"
	"encoding/pem"
	"github.com/emmansun/gmsm/pkcs8"
	"github.com/emmansun/gmsm/sm2"
	"github.com/emmansun/gmsm/smx509"
	"log"
	"os"
)

func main() {
	priKey, err := sm2.GenerateKey(rand.Reader)
	if err != nil {
		log.Println(err)
	}
	//derStream, err := pkcs8.MarshalPrivateKey(priKey, []byte(""), pkcs8.DefaultOpts)
	//derStream, err := x509.MarshalPKCS8PrivateKey(&priKey.PrivateKey)
	key, err := smx509.MarshalSM2PrivateKey(priKey)

	key2, err := pkcs8.MarshalPrivateKey(priKey, []byte(""), pkcs8.DefaultOpts)
	if err != nil {
		panic(err)
	}
	block := pem.Block{
		Type:  "SM2 PRIVATE KEY", //"RSA PRIVATE KEY",
		Bytes: key,
	}
	// 4. 创建文件
	privFile, err := os.Create("./key/private.pem")
	if err != nil {
		panic(err)
	}
	defer privFile.Close()
	// 5. 使用pem编码, 并将数据写入文件中
	err = pem.Encode(privFile, &block)
	if err != nil {
		panic(err)
	}

	////
	block2 := pem.Block{
		Type:  "SM2 PRIVATE KEY", //"RSA PRIVATE KEY",
		Bytes: key2,
	}
	privFile2, err := os.Create("./key/private2.pem")
	if err != nil {
		panic(err)
	}
	defer privFile2.Close()
	// 5. 使用pem编码, 并将数据写入文件中
	err = pem.Encode(privFile2, &block2)
	if err != nil {
		panic(err)
	}
	////
	// 6. 最后的时候关闭文件
	defer privFile.Close()
	defer privFile2.Close()
}
